<template>
  <div class="login-box">
    <el-card style="max-width: 480px">
      <template #header>
        <div>
          <span>微商城管理系统</span>
        </div>
      </template>
      <el-form
        label-width="auto"
        :model="formVal"
        :rules="formRules"
        ref="formRef"
      >
        <el-form-item
          label="用户名"
          prop="userName"
        >
          <el-input
            style="width: 240px"
            placeholder="请输入用户名"
            :prefix-icon="User"
            v-model="formVal.userName"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="passWord"
        >
          <el-input
            style="width: 240px"
            type="password"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
            v-model="formVal.passWord"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="login"
          >登 录</el-button>
          <el-button @click="clear">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>

<script setup>
  import { ElMessage } from 'element-plus';
  import { reactive, ref } from 'vue';
  import { User, Lock } from '@element-plus/icons-vue';
  import { Login } from '../api/apiByLogin.js';
  import { useRouter, useRoute } from 'vue-router';
  import { useTokenStore } from '../store/tokenStore';
  import { useAdminStore } from '../store/adminStore'
  import { useLoginTimeStore } from '../store/loginTimeStore.js'
  import {getAvatarURL}  from '../api/apiByUser.js'
  import {useAvatarStore} from '../store/avatar.js';

  const tokenStore = useTokenStore();
  const adminStore = useAdminStore();
  const router = useRouter();
  const route = useRoute();
  const loginTimeStore = useLoginTimeStore();
  const avatarStore = useAvatarStore();

  const formVal = reactive({
    userName: 'admin',
    passWord: '123'
  });
  const formRules = reactive({
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 8, message: '用户名长度应为3-8个字符', trigger: 'blur' }
    ],
    passWord: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 3, max: 12, message: '密码长度应为3-12个字符', trigger: 'blur' }
    ]
  });

  const formRef = ref(null);

  const clear = () => {
    formRef.value.resetFields();
  };


  const getCurrentTimeFormatted = () =>{
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

  const checkLogin = async (formVal) => {
    const resp = await Login(formVal);
    console.log(resp);
    
    if (resp && resp != null) {
      tokenStore.updateToken(resp.token);
      adminStore.updateAdmin(formVal.userName);
      loginTimeStore.updateLoginTime(getCurrentTimeFormatted());
      const avatarURL = await getAvatarURL(formVal.userName);
      console.log(avatarURL);
      
      avatarStore.updateAvatar('http://localhost:8080/'+avatarURL);

      // 优先级： 用户有期望登录的页面 > 首页
      router.push(route.query['redirectUrl'] || '/index');
    } else {
      formRef.value.resetFields();
    }
  };

  const login = () => {
    formRef.value.validate(async (flag) => {
      if (!flag) {
        ElMessage.error('请核对表单数据再提交！！！');
      } else {
        checkLogin(formVal);
      }
    });
  };
</script>

<style scope lang="scss">
  .login-box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    background: url('../../public/images/loginBg.jpg') center/cover;

    .el-card {
      width: 600px;

      // :deep(选择器)： scss 样式穿透的语法，什么时候需要⽤到样式穿透：
      // 1. 当前组件的 style 添加了 scoped
      // 2. 修改的是第三⽅组件内部元素的样式
      :deep(.el-card__header) {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 70px;
        // 注意：var(css变量)，好处就是利于今后的代码维护和修改
        background: var(--el-color-primary);
        color: #fff;

        span {
          font-size: 16px;
          font-weight: 400;
        }
      }

      .el-form {
        padding: 15px 25px;

        .el-form-item:nth-child(2) {
          margin: 20px 0;
        }

        .el-input {
          height: 45px;
        }

        .el-button {
          width: 65px;
          height: 35px;
        }
      }
    }
  }

</style>